<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); 

class Block_Post_Filter_Status extends Block_Post_Filter_Abstract {

	private $_where = '';
	
	public function __construct() {
		$this->_requestVar = 'status';
		$this->setTemplate('post/filter/status');
	}
	
	public function apply() {
		if (App::get($this->getRequestVar())) {
			// get applied values
			$status = App::get($this->getRequestVar());
			$this->_appliedValues = array($status);
			
			// append filter to collection
			$select = $this->getLayer()->getCollection()->getSelect();
			$this->_where = 'post.status = '.$status;
			$select->where($this->_where);
		}
	}
	
	public function getItems() {
		// remove filter part of this filter in select statement
		$select = clone $this->getLayer()->getCollection()->getSelect();
		$select->setPart(Core_Db_Select::COLUMNS, array('post.id'))
			->resetPart(Core_Db_Select::LIMIT)
			->resetPart(Core_Db_Select::ORDER);

		$where = $select->getPart(Core_Db_Select::WHERE);
		if (($key = array_search($this->_where, $where)) !== false)
			unset($where[$key]);
		$select->setPart(Core_Db_Select::WHERE, $where);

		$select2 = 'SELECT status.*, COUNT(post.id) as post_count '.
			'FROM status JOIN post ON post.status = status.id '.
			'WHERE post.id IN ('.(string)$select.') '.
			'GROUP  BY status.id '.
			'ORDER BY status.sort_order ASC';

		$rows = App::db()->query($select2)->result_array();
		
		// prepare filter items
		$items = array();
		foreach($rows as $row) {
			$item = array(
				'label' => $row['label'],
				'value' => $row['id'],
				'count' => $row['post_count'],
				'selected' => in_array($row['id'], $this->getAppliedValues()),
				'url' => $this->getItemUrl($row['id'])
			);
			array_push($items, $item);
		}
		return $items;
	}
	
}